package com.esiag.pdsteam.measureagainst;


import java.io.IOException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import com.esiag.isidis.fi.pdsTeam.send.beans.Information;
public class Consumer implements MessageListener,Iconsumer{

	private static final String URL = ActiveMQConnection.DEFAULT_BROKER_URL;
	private static final String QUEUE = "QUEUE-PDSTeam";
	TextMessage tmsg;
	
	
	
	public TextMessage getTmsg() {
		return tmsg;
	}

	public void setTmsg(TextMessage tmsg) {
		this.tmsg = tmsg;
	}

	public Consumer() throws JMSException {
		
		ConnectionFactory factory = new ActiveMQConnectionFactory();
		Connection connection = factory.createConnection();
		connection.start();
		
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		Destination destination = session.createQueue(QUEUE);
		
		MessageConsumer consumer = session.createConsumer(destination);
		
		consumer.setMessageListener(this);
		
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		connection.close();
	}
	
	public static void main(String[] args) throws JMSException {
		new Consumer();
	}

	
	public void onMessage(Message msg) {
		if(msg instanceof TextMessage){
			tmsg = (TextMessage) msg;
			try {
				System.out.println("Consumer :" + tmsg.getText());
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		else if(msg instanceof ObjectMessage){
			ObjectMessage ObjMsg = (ObjectMessage)msg;
			try {
				Information information = (Information) ObjMsg.getObject();
				System.out.println(information.getId() + " , " + information.getDescri());
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}

	public String getTexte() {
		try {
			return tmsg.getText();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	
}